<template>
  <div class="role">
    <page-search
      :searchFormConfig="searchFormConfig"
      @resetBtnClick="handleResetBtn"
      @searchBtnClick="handleSearchBtn"
    ></page-search>
    <page-content
      :contentTableConfig="contentTableConfig"
      @createBtnClick="handleCreateData"
      @updateBtnClick="handleUpdateData"
      pageName="role"
      ref="pageContentRef"
    ></page-content>
    <page-modal
      ref="pageModalRef"
      :modalConfig="modalDialogConfig"
      pageName="role"
      :defaultInfo="defaultInfo"
      :otherInfo="otherInfo"
    >
      <div class="modal-tree">
        <el-tree
          ref="elTreeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckChange"
        >
        </el-tree>
      </div>
    </page-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, nextTick } from 'vue'
import { useStore } from '@/store'
import { mapMenusToLeafNodes } from '@/utils/map-menus'
import { ElTree } from 'element-plus'

import { contentTableConfig } from './config/content-config'
import { searchFormConfig } from './config/search-config'
import { modalDialogConfig } from './config/modal-config'

import { usePageSearch } from '@/hooks/usePageSearch'
import { usePageModal } from '@/hooks/usePageModal'

export default defineComponent({
  name: 'role',
  setup() {
    const [pageContentRef, handleResetBtn, handleSearchBtn] = usePageSearch()

    // 菜单编辑回填逻辑
    const elTreeRef = ref<InstanceType<typeof ElTree>>()
    const editCallback = (item: any) => {
      // 将每个选项节点转为叶子节点
      const leafKeys = mapMenusToLeafNodes(item.menuList)
      // 点击编辑进行编辑执行回调函数时,elTree的ref还未绑定上
      nextTick(() => {
        elTreeRef.value?.setCheckedKeys(leafKeys, false)
      })
    }

    const [pageModalRef, defaultInfo, handleCreateData, handleUpdateData] =
      usePageModal(undefined, editCallback)

    // 拿到菜单列表
    const store = useStore()
    const menus = computed(() => store.state.entireMenu)

    // 拿到checked的菜单,传给pageModal,拼接到请求体里
    const otherInfo = ref({})
    const handleCheckChange = (data1: any, data2: any) => {
      const checkedKeys = data2.checkedKeys
      const halfCheckedKeys = data2.halfCheckedKeys

      const menuList = [...checkedKeys, ...halfCheckedKeys]
      otherInfo.value = { menuList }
    }

    return {
      searchFormConfig,
      contentTableConfig,
      modalDialogConfig,
      pageContentRef,
      pageModalRef,
      handleResetBtn,
      handleSearchBtn,
      handleCreateData,
      handleUpdateData,
      defaultInfo,
      menus,
      otherInfo,
      handleCheckChange,
      elTreeRef
    }
  }
})
</script>

<style scoped lang="less">
.modal-tree {
  margin-left: 78px;
}
</style>
